package com.baitiaojun.bulletscreen.support;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @类名 RedisSuport
 * @作者 白条君
 * @创建日期 2022/10/28 15:15
 * @版本 1.0
 */
@Slf4j
@Getter
@Component("redisSupport")
public class RedisSupport {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public ValueOperations<String, Object> string() {
        return redisTemplate.opsForValue();
    }

    public <T> void setValue(String key, T value, long timeout, TimeUnit unit) {
        string().set(key, value, timeout, unit);
    }

    public Object getValue(String key) {
        return string().get(key);
    }

    public <T> Boolean setNx(String key, T value, Long expire, TimeUnit timeUnit) {
        Boolean result = redisTemplate.execute((RedisCallback<Boolean>) connection ->
                    connection.set(key.getBytes(StandardCharsets.UTF_8)
                            , String.valueOf(value).getBytes(StandardCharsets.UTF_8)
                            , Expiration.from(expire, timeUnit)
                            , RedisStringCommands.SetOption.ifAbsent()));
        return Boolean.TRUE.equals(result);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public HashOperations<String, String, Object> hash() {
        return redisTemplate.opsForHash();
    }

    public Object getHash(String key, String field) {
        return hash().get(key, field);
    }
}